package com.scalar.chiptrack.reports.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.reports.actioncommands.JasperReportsActionCommandFactory;
import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.users.User;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 *
 */
public class BaseJasperReportsAction extends ChipTrackAction {

    @Override
    public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        HttpSession pSession = null;
        User pUser = null;
        // Assign current session
        pSession = httpServletRequest.getSession();

        // Get current user
        pUser = (User) pSession.getAttribute(SessionKeys.USER_KEY);

        // Redirect the user to login page, if he/she is not logged in
        if (pUser == null) {
            //todo need to forward to login page or simply return a message saying not loggedin based on the request type.
            pSession.setAttribute(SessionKeys.SOURCE_PAGE_KEY, httpServletRequest.getServletPath() + "?" + httpServletRequest.getQueryString());
            return (actionMapping.findForward(SessionKeys.ACTION_FORWARD_KEY_LOGIN));
        }
        // Create and add Errors HashMap to the request
        httpServletRequest.setAttribute(SessionKeys.ERROR_MESSAGES, new HashMap());
        // Create and add Info Messages HashMap to the request
        httpServletRequest.setAttribute(SessionKeys.INFO_MESSAGES, new HashMap());
        String action = httpServletRequest.getParameter(Constants.REQUEST_PARAM_ACTION);
        ActionCommand actionCommand = null;
        actionCommand = JasperReportsActionCommandFactory.getActionCommand(action);
        ActionForward actionForward = actionCommand.execute(actionMapping, actionForm, httpServletRequest, httpServletResponse);

        return actionForward;
    }
}
